package com.itheima.tool;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Component
public class AliCloudUtils {


    private String endpoint = "https://oss-cn-beijing.aliyuncs.com";

    private String bucketName = "web-426";

    private String AccessKeyId = "LTAI5tGgbvVWx1gAXUs9YspN";

    private String AccessKeySecret = "1P5Q8iNqb1ih7hrpopRvSOccamiDbu";


    public String AliCloud(MultipartFile file) throws IOException {

        //调用Multipart变量的方法,获取到输入流
        InputStream inputStream = file.getInputStream();
        String startname = file.getOriginalFilename();
        String filename = UUID.randomUUID().toString() +
                startname.substring(startname.lastIndexOf("."));

        //创建对象,调用方法把文件上传到bucket中,需要的数据有bucketname,name,输入流
        OSS oosClient = new OSSClientBuilder().build(endpoint, AccessKeyId, AccessKeySecret);
        oosClient.putObject(bucketName, filename, inputStream);

        //新建一个变量返回网址,存入database中
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + filename;
        oosClient.shutdown();
        return url;
    }
}
